< previous page page_228 next page >

Page 228
Now look at a brief example of a procedure that uses parameters. Suppose your program needs to log all its operations and errors to a text file. A procedure that handles writing messages to the log file, along with a date and time, could be very useful:
Sub LogPrint(sMessage As String)
    Dim nFileNum As Integer
    nFileNum = FreeFile
    Open "C:\EVENTLOG.TXT" for append as #nFileNum
    Print #nFileNum, Now & " - " & sMessage
    Close #nFileNum
End Sub
The following line of code calls the procedure. When calling a procedure, you can supply values for its arguments using either a variable, a literal string, or a combination of the two:
LogPrint "Error Opening file " & sUserFile
The LogPrint procedure is simple, yet it saves a lot of time in the long run. It makes the calling code shorter and more readable. In addition, if you ever want to change the format of the output file or change the destination of the log information from a text file to a database, printer, or pager, you have to modify only the LogPrint function itself.
CAUTION
Typically, you must include the same number of parameters in the calling statement as are present in the definition of the procedure. Also, the values supplied by the calling statement must match the data types expected by the procedure. Violating either of these conditions results in an error when you run your program.

At the start of this section, I listed two methods of calling a procedure. The following line of code calls the LogPrint procedure using the other syntax:
Call LogPrint ("The server was rebooted")
As you can see, the Call keyword itself is optional when calling the procedure. If you use the Call keyword, you must include the parameters in a set of parentheses. I recommend using the syntax that does not use Call. As you will see after looking at the examples in the next section, this approach makes distinguishing between procedure calls and function calls easier.
Passing Data to a Procedure
You can get information into a procedure for processing in two ways: you can define the variables as public variables that are available everywhere in your program, or you can pass the variables directly to the procedure in the calling statement.
For example, you could add a second argument to the LogPrint procedure that allows it to work with multiple files:
Sub LogPrint(sLogFile As String, sMessage As String)
    Dim nFileNum As Integer
    nFileNum = FreeFile
    Open sLogFile for Append as #nFileNum
    Print #nFileNum, Now & " - " & sMessage
    Close #nFileNum
End Sub

 
< previous page page_228 next page >